package myapp.DAO;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import staticClass.MyRequest;
import staticClass.XmppConnection;

import android.util.Log;

import myapp.DTO.FriendshipDTO;
import myapp.DTO.UserDTO;
import myapp.EnumAndConstans.Constants;
import myapp.helper.Utils;

public class UserDAO extends DataProvider {
	private final String url = "User";

	public String getMyName(String email, String pwd) {
		if (! XmppConnection.isConnected())
			return null;
		String request = chatBaseHost + url + "?email=" + email + "&pwd=" + pwd;

		String strResponse = requestGET(request);
		Log.i("UserDAO", "[getMyName] res:"+strResponse);
		UserDTO userDTO = parseJsonResponseToObj(strResponse);
		if (userDTO != null) {
			String userName = userDTO.name;
			if (userDTO.id == Constants.NOT_AVAILABLE){
				userName = Constants.USERNAME_NOT_AVAILABLE;
			}
			Log.i("UserDAO", "[getMyName] userName=" + userDTO.name);
			return userName;
		}
		return null;
	}

	public ArrayList<UserDTO> getAllFriends(String email, String pwd) {
		if (! XmppConnection.isConnected())
			return new ArrayList<UserDTO>();
		String request = chatBaseHost + url + "?op=" + Constants.GET_ALL_FRIENDS
				+ "&email=" + email + "&pwd=" + pwd;

		String strResponse = requestGET(request);

		return parseJsonResponseToArr(strResponse);
	}

	public ArrayList<UserDTO> getOnlineFriends(String email, String pwd) {
		if (! XmppConnection.isConnected())
			return new ArrayList<UserDTO>();
		String request = chatBaseHost + url + "?op="
				+ Constants.GET_ONLINES_FRIENDS + "&email=" + email + "&pwd="
				+ pwd;

		String strResponse = requestGET(request);

		return parseJsonResponseToArr(strResponse);
	}

	public ArrayList<UserDTO> getAllRequesters(String email, String pwd) {
		if (! XmppConnection.isConnected())
			return new ArrayList<UserDTO>();
		String request = chatBaseHost + url + "?op=" + Constants.GET_ALL_REQUESTERS
				+ "&email=" + email + "&pwd=" + pwd;
		String strResponse = requestGET(request);

		return parseJsonResponseToArr(strResponse);
	}

	public Boolean sendFriendRequest(String yourEmail, String yourFriendEmail) {
		if (! XmppConnection.isConnected())
			return false;
		String request = chatBaseHost + "requestfriend";
		FriendshipDTO friendship = new FriendshipDTO(yourEmail, yourFriendEmail);
		// String data = null;
		try {
			JSONObject json = friendship.toJson();
			MyRequest.postDataJson(request, json);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("UserDAO", "[sendFriendRequest] exception:" + e.getMessage());
			return false;
		}
		return true;
	}

	public void sendAcceptFriendRequest(String receiverEmail,
			String requesterEmail) {
		if (! XmppConnection.isConnected())
			return;
		String requestUrl = chatBaseHost + "friendship";
		FriendshipDTO friendship = new FriendshipDTO(requesterEmail,
				receiverEmail);
		// String data = Utils.makeDataRequest(receiverEmail, requesterEmail);
		try {
			MyRequest.postDataJson(requestUrl, friendship.toJson());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("UserDAO",
					"[sendAcceptFriendRequest] exception:" + e.getMessage());
			return;
		}
		// requestPOST(requestUrl, data);
	}

	public String sendRemoveFriendshipRequest(String userEmail, String friendEmail) {
		if (! XmppConnection.isConnected())
			return "Remove failed.";
		String url = chatBaseHost + "friendship/delete";
		FriendshipDTO friendship = new FriendshipDTO(userEmail, friendEmail);
		try {
			JSONObject json = friendship.toJson();
			MyRequest.postDataJson(url, json);
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("UserDAO", "[sendRemoveFriendshipRequest] exception:" + e.getMessage() + e.getLocalizedMessage());
			return "Remove failed.";
		}
		return "Remove Succeed.";
	}
	
	private UserDTO jsonToObject(JSONObject json) {
		try {
			return new UserDTO(json.getInt("Id"), json.getString("Email"),
					"", // Don't get pwd of friends
					json.getDouble("Latitude"), json.getDouble("Longtitude"),
					json.getString("Name"), json.getInt("AvatarId"),
					json.getInt("Available"));
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("UserDAO", "[jsonToObject] exception:" + e.getMessage());
		}
		return null;
	}

	private UserDTO parseJsonResponseToObj(String strResponse) {
		if (strResponse == null)
			return null;
		
		JSONObject json = null;
		Log.i("UserDAO", "[parseJsonResponseToObj] jsonStr: " + strResponse);

		try {
			json = new JSONObject(strResponse);
			Log.i("UserDAO",
					"[parseJsonResponseToObj] json = " + json.toString());
		} catch (Exception e) {
			// TODO: handle exception
			Log.i("UserDAO",
					"[parseJsonResponseToObj] Exception: " + e.getMessage());
			return null;
		}
		return jsonToObject(json);
	}

	private ArrayList<UserDTO> parseJsonResponseToArr(String strResponse) {
		JSONArray jsons;
		ArrayList<UserDTO> users = new ArrayList<UserDTO>();

		try {
			jsons = new JSONArray(strResponse);
			Log.i("UserDAO", "[parseJSONArr] jsonsLength = " + jsons.length());
			for (int i = 0; i < jsons.length(); i++) {
				users.add(jsonToObject(jsons.getJSONObject(i)));
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.i("UserDAO", "[parseJSONArr] Exception: " + e.getMessage());
		}
		return users;
	}

	public void sendRejectFriendRequest(String receiverEmail,
			String requesterEmail) {
		
		if (! XmppConnection.isConnected())
			return;
		
		// TODO Auto-generated method stub
		String requestUrl = chatBaseHost + "requestfriend" + "/"
				+ Constants.REQUEST_REJECT;
		String data = Utils.makeDataRequest(receiverEmail, requesterEmail);
		requestPOST(requestUrl, data);
	}


	public String sendAddNewFriendRequest(String userEmail, String name,
			String pwd) {
		if (! XmppConnection.isConnected())
			return null;
		String requestUrl = chatBaseHost + "user/?" + "userEmail=" + userEmail
				+ "&name=" + name;
		String data = pwd;
		requestPOST(requestUrl, data);
		return null;
	}

	public String updateUser(UserDTO info) {
		if (! XmppConnection.isConnected())
			return null;
		
		String requestUrl = chatBaseHost + "user";
		try {
			JSONObject json = info.toJson();
			MyRequest.postDataJson(requestUrl, json);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("UserDAO",
					"[updateUser] ex:" + e.getMessage()
							+ e.getLocalizedMessage());
		}

		return null;
	}
}
